package repositories

import (
	"gcopyright/models"
)

// 查询ether_table表account 出现次数，和整行数据
func (r *RepositoriesSqlite) QuernEtherTableAccountsFrequency(hexAddress string) ([]models.EtherTable, int) {
	sql := r.sqlite

	rows, err := sql.Query("SELECT * FROM ether_table WHERE account = ?", hexAddress)
	checkErr(err)
	var ether = models.EtherTable{}
	var arrayEther []models.EtherTable
	for rows.Next() {
		err = rows.Scan(&ether.Account, &ether.DeployAddress, &ether.Content, &ether.Hash, &ether.Timestamp, &ether.Author)
		arrayEther = append(arrayEther, ether)
		checkErr(err)
	}
	return arrayEther, len(arrayEther)
}

//func(r *RepositoriesSqlite)Q(){
//	sql := r.sqlite
//	rows, err := sql.Query("SELECT * FROM PEOPLE WHERE NAME = WANGTING" )
//
//}
/*type EtherTable struct {
	Account       string `json:"account"`
	DeployAddress string `json:"deploy_address"`
	Content       string `json:"content"`
	Hash          string `json:"hash"`
	Timestamp     string `json:"timestamp"`
	Author        string `json:"author"`
}*/

func (r *RepositoriesSqlite) InsertEtherTable(Account, DeployAddress, Content, Hash, Timestamp, Author string) {
	sql := r.sqlite
	stmt, err := sql.Prepare("INSERT INTO ether_table(account, deploy_address , content,hash,Timestamp,author) values(?,?,?,?,?,?)")
	checkErr(err)
	res, err := stmt.Exec(Account, DeployAddress, Content, Hash, Timestamp, Author)
	checkErr(err)
	_, err = res.LastInsertId()
	checkErr(err)
}

func (r *RepositoriesSqlite) DeleteEtherTable() {

	sql := r.sqlite
	sqlStmt := `
	DROP TABLE ether_table;
	`
	_, err := sql.Exec(sqlStmt)
	checkErr(err)
}

// 创建 EtherTable
func (r *RepositoriesSqlite) CreateEtherTable() {
	sql := r.sqlite
	sqlStmt := `
	create table ether_table (account text , deploy_address text ,content text,hash text,Timestamp text ,author text);
	`
	_, err := sql.Exec(sqlStmt)
	checkErr(err)
}

func (r *RepositoriesSqlite) QuernEtherTableAllElement() []models.DeploySuccess {
	sql := r.sqlite
	rows, err := sql.Query("SELECT * FROM ether_table ")
	checkErr(err)
	var fileInfo models.EtherTable
	var front models.DeploySuccess
	var arrayFront []models.DeploySuccess
	for rows.Next() {
		err = rows.Scan(
			&fileInfo.Account,
			&fileInfo.DeployAddress,
			&fileInfo.Content,
			&fileInfo.Hash,
			&fileInfo.Timestamp,
			&fileInfo.Author)
		front = models.DeploySuccess{
			Title:     fileInfo.Content,
			Timestamp: fileInfo.Timestamp,
			Address:   fileInfo.DeployAddress,
		}
		arrayFront = append(arrayFront, front)
		checkErr(err)
	}
	return arrayFront
}

//去重
func (r *RepositoriesSqlite) checkRepeat(s string) bool {
	sql := r.sqlite
	rows, err := sql.Query("SELECT * FROM ether_table WHERE hash = ?", s)
	checkErr(err)
	var fileInfo = models.EtherTable{}
	for rows.Next() {
		err = rows.Scan(
			&fileInfo.Account,
			&fileInfo.DeployAddress,
			&fileInfo.Content,
			&fileInfo.Hash,
			&fileInfo.Timestamp,
			&fileInfo.Author)
		checkErr(err)
	}
	if fileInfo.Hash == "" {
		return true
	} else {
		return false

	}
}
